2.3 创建表格时修改属性
在使用pd.DataFrame()函数创建表格时,对index参数设置行索引,对columns参数设置列索引,对dtype参数设置数据类型。
pd.DataFrame()函数中的dtype参数只能对整个表格设置,如果需要对指定列设置类型,data参数只能是数组,并且是在生成数组时的设置。
2.3.1 使用pd.DataFrame()函数修改属性
import pandas as pd
df=pd.DataFrame( data =[[ 1,2,3 ],[ 4,5,6 ],[ 7,8,9 ],[ 10,11,12 ]],
index =[ "a","b","c","d" ],
columns =[ "100","200","300" ],
dtype = "float"
)
print (df)
返回
100 | 200 | 300 | |
---|---|---|---|
a | 1.0 | 2.0 | 3.0 |
b | 4.0 | 5.0 | 6.0 |
c | 7.0 | 8.0 | 9.0 |
d | 10.0 | 11.0 | 12.0 |
2.3.2 生成组数组时修改dtype属性
import pandas as pd,numpy as np
tp=np.dtype([( "名字" , "U4" ),( "年龄" , "int" ),( "成绩" , "float" )])
arr=np.array([
( "张三" ,12,88.6 ),
( "李四",45,99.3 ),
( "王五",28,79.6 )
], dtype =tp)
df=pd.DataFrame( data =arr)
print (df)
返回
名字 | 年龄 | 成绩 | |
---|---|---|---|
0 | 张三 | 12 | 88.6 |
1 | 李四 | 45 | 99.3 |
2 | 王五 | 28 | 79.6 |